package com.zzq.interceptors;

import com.zzq.context.BaseContext;
import com.zzq.tools.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        //如果令牌为空，则返回401
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //得到当前用户Id
            String userId = String.valueOf(claims.get("username").toString());
            log.info("当前用户Id为:{}",userId);
            BaseContext.setCurrentId(userId);
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }
}
